package com.ljf.weather.service;

import com.ljf.weather.domain.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeatherService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RedisTemplate redisTemplate;

//    String url = "https://apis.tianapi.com/tianqi/index?key=6e08fd388b0c7d78b2615eed6f1cfb7b&city=101020100&type=1";
    //访问第三方接口获取天气数据
    @Value("${url}")
    String url;
    @Value("${apikey}")
    String key;
    @Value("${type}")
    Integer type;

//   100分
    public WeatherResponse getWeather(String cityId){
        WeatherResponse weatherResponse = null;
        String searchUrl=url+"key="+key+"&city="+cityId+"&type="+type;
        // 先查缓存是否有数据 没有再调用接口查询
        weatherResponse = (WeatherResponse) redisTemplate.opsForHash().get("weatherTable",cityId);

        if(weatherResponse == null){
            synchronized (this){
                weatherResponse = (WeatherResponse) redisTemplate.opsForHash().get("weatherTable",cityId);
                if(weatherResponse == null){
                    //调用接口查询
                    weatherResponse = restTemplate.getForObject(searchUrl,WeatherResponse.class);
                    //放入redis缓存
                    redisTemplate.opsForHash().put("weatherTable",cityId,weatherResponse);
                }
            }

        }
        return weatherResponse;
    }

}

//    60分
//    public String getWeather(String cityId){
//        String searchUrl = url+"key="+key+"&city="+cityId+"&type="+type;
//        return restTemplate.getForObject(searchUrl,String.class);
//    }

//    70分
//    public WeatherResponse getWeather(String cityId){
//        String searchUrl = url+"key="+key+"&city="+cityId+"&type="+type;
//        return restTemplate.getForObject(searchUrl,WeatherResponse.class);
//    }

//   90分
//    public WeatherResponse getWeather(String cityId){
//        WeatherResponse weatherResponse = null;
//        String searchUrl = url+"key="+key+"&city="+cityId+"&type="+type;
//        // 先查缓存是否有数据 没有再调用接口查询
//        weatherResponse = (WeatherResponse) redisTemplate.opsForHash().get("weatherTable",cityId);
//
//        if(weatherResponse == null){
//            //调用接口查询
//            weatherResponse = restTemplate.getForObject(searchUrl,WeatherResponse.class);
//            //放入redis缓存
//            redisTemplate.opsForHash().put("weatherTable",cityId,weatherResponse);
//        }
//        return weatherResponse;
//    }